package com.tide.crm.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import com.tide.crm.dao.ConvergeAttachmentDao;
import com.tide.crm.model.ConvergeAttachment;
import com.tide.crm.service.ConvergeAttachmentService;
import com.tide.crm.utils.CosClientUtil;
import com.tide.crm.utils.CreateIdUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.qcloud.cos.COSClient;

@Service("convergeAttachmentService")
public class ConvergeAttachmentServiceImpl implements ConvergeAttachmentService {

	
	@Resource(name="convergeAttachmentDao")
	private ConvergeAttachmentDao convergeAttachmentDao;
	
	
//	@Value("${uploadFile.qualification}")
//	private String qualification;
//	@Value("${uploadFile.goodPath}")
//	private String goods;
	@Value("${uploadFile.serverUrl}")
	private String serverUrl;
	
	@Value("${uploadFile.accessId}")
	private String accessId;
	@Value("${uploadFile.secretKey}")
	private String secretKey;
	@Value("${uploadFile.bucketName}")
	private String bucketName;
	@Value("${uploadFile.appId}")
	private String appId;
	@Value("${uploadFile.regionId}")
	private String regionId;
	
	
	@Override
	public ConvergeAttachment getConvergeAttachmentById(Long id) {
		return convergeAttachmentDao.getById(id);
	}


	@Override
	public ConvergeAttachment saveAttachment(MultipartFile file,String filePath) throws IOException {
		// TODO Auto-generated method stub
		// 获取MulipartFile对象 
		String extName = ""; 
		Date date = new Date();
        byte[] bytes = file.getBytes(); 
        String origName = file.getOriginalFilename(); 
        if (origName.lastIndexOf(".") >= 0) {
            extName = origName.substring(origName.lastIndexOf("."));
        }
        String name = UUID.randomUUID().toString();
        String destFile= name+extName;
        
        //向附件表存入信息
        ConvergeAttachment attachment = new ConvergeAttachment();
        attachment.setId(CreateIdUtils.getEntityId());
        attachment.setCreateDate(date);
        attachment.setModifyDate(date);
        attachment.setFileSuffix(extName);
        attachment.setFileType(1);
        attachment.setOrderList(0);
        attachment.setSourceName(origName);
        attachment.setStatus(0);
        attachment.setPath(serverUrl+filePath+"/"+destFile);
        attachment.setOsspath(filePath+"/"+destFile);
        convergeAttachmentDao.save(attachment);
        
        //将文件存入腾讯云
        COSClient  client =  CosClientUtil.getCosClient(accessId, secretKey, regionId);
        String result = CosClientUtil.uploadFile(bucketName,filePath+"/"+destFile,file.getInputStream(),client);
        
		return attachment;
	}
	
	
}
